<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天调试 - BoLe HR</title>
    <!-- 引入markdown渲染库 -->
    <script src="https://cdn.jsdelivr.net/npm/marked@12.0.0/marked.min.js"></script>
    <style>
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0; 
            padding: 20px; 
            background: #f5f5f5;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .chat-panel, .debug-panel {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .chat-history {
            height: 400px;
            border: 1px solid #ddd;
            padding: 15px;
            overflow-y: auto;
            margin-bottom: 15px;
            background: #fafafa;
        }
        
        .message-wrapper {
            display: flex;
            margin-bottom: 15px;
        }
        
        .user-message-wrapper {
            justify-content: flex-end;
        }
        
        .ai-message-wrapper {
            justify-content: flex-start;
        }
        
        .message {
            display: flex;
            max-width: 70%;
            align-items: flex-end;
            gap: 10px;
        }
        
        .user-message {
            flex-direction: row-reverse;
        }
        
        .message-content {
            padding: 12px 16px;
            border-radius: 18px;
            max-width: 100%;
            word-wrap: break-word;
        }
        
        .user-message .message-content {
            background: #667eea;
            color: white;
        }
        
        .ai-message .message-content {
            background: #e9ecef;
            color: #333;
        }
        
        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }
        
        .user-avatar {
            background: #667eea;
            color: white;
        }
        
        .ai-avatar {
            background: #6c757d;
            color: white;
        }
        
        .loading-spinner {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .input-area {
            display: flex;
            gap: 10px;
        }
        
        input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
        }
        
        button {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
        }
        
        button:hover {
            background: #5a67d8;
        }
        
        .debug-log {
            height: 500px;
            background: #1a1a1a;
            color: #00ff00;
            padding: 15px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            overflow-y: auto;
            border-radius: 5px;
        }
        
        .suggestions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        
        .suggestion {
            padding: 5px 12px;
            background: #e9ecef;
            border: none;
            border-radius: 15px;
            font-size: 12px;
            cursor: pointer;
        }
        
        .suggestion:hover {
            background: #667eea;
            color: white;
        }
        
        /* Markdown样式 */
        .message-content h1, .message-content h2, .message-content h3, .message-content h4, .message-content h5, .message-content h6 {
            margin: 0.5em 0 0.3em 0;
            color: #333;
            font-weight: bold;
        }
        
        .message-content h1 { font-size: 1.5em; }
        .message-content h2 { font-size: 1.3em; }
        .message-content h3 { font-size: 1.2em; }
        
        .message-content p {
            margin: 0.5em 0;
            line-height: 1.6;
        }
        
        .message-content code {
            background: #f4f4f4;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            color: #d63384;
        }
        
        .ai-message .message-content code {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        
        .message-content pre {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 12px;
            margin: 8px 0;
            overflow-x: auto;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.85em;
            line-height: 1.4;
        }
        
        .message-content pre code {
            background: none;
            padding: 0;
            color: #212529;
        }
        
        .message-content ul, .message-content ol {
            margin: 0.5em 0;
            padding-left: 1.5em;
        }
        
        .message-content li {
            margin: 0.3em 0;
            line-height: 1.5;
        }
        
        .message-content blockquote {
            border-left: 4px solid #667eea;
            margin: 0.5em 0;
            padding: 0.5em 1em;
            background: #f8f9fa;
            color: #6c757d;
            font-style: italic;
        }
        
        .message-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 0.5em 0;
            font-size: 0.9em;
        }
        
        .message-content th, .message-content td {
            border: 1px solid #dee2e6;
            padding: 8px 12px;
            text-align: left;
        }
        
        .message-content th {
            background: #f8f9fa;
            font-weight: bold;
        }
        
        .message-content strong, .message-content b {
            font-weight: bold;
            color: #495057;
        }
        
        .message-content em, .message-content i {
            font-style: italic;
        }
        
        .message-content hr {
            border: none;
            border-top: 2px solid #e9ecef;
            margin: 1em 0;
        }
        
        .message-content a {
            color: #667eea;
            text-decoration: none;
        }
        
        .message-content a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <h1>🔍 聊天功能调试界面</h1>
    
    <div class="container">
        <div class="chat-panel">
            <h2>💬 聊天测试</h2>
            
            <div class="suggestions">
                <button class="suggestion" onclick="testMessage('你好')">你好</button>
                <button class="suggestion" onclick="testMessage('筛选Python候选人')">筛选Python候选人</button>
                <button class="suggestion" onclick="testMessage('找几个有5年经验的工程师')">5年经验工程师</button>
                <button class="suggestion" onclick="testMessage('所有候选人列表')">所有候选人列表</button>
                <button class="suggestion" onclick="clearChat()">清空</button>
            </div>
            
            <div class="chat-history" id="chatHistory"></div>
            
            <div class="input-area">
                <input type="text" id="messageInput" placeholder="输入测试消息..." onkeypress="if(event.key==='Enter') sendMessage()">
                <button onclick="sendMessage()">发送</button>
            </div>
        </div>
        
        <div class="debug-panel">
            <h2>🐛 调试日志</h2>
            <div class="debug-log" id="debugLog"></div>
        </div>
    </div>

    <script>
        const apiBaseUrl = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/api`;
        let sending = false;
        
        function debugLog(message, type = 'info') {
            const debugDiv = document.getElementById('debugLog');
            const time = new Date().toLocaleTimeString();
            const colors = {
                info: '#00ff00',
                error: '#ff4444',
                warn: '#ffaa00',
                success: '#00dd00'
            };
            
            debugDiv.innerHTML += `<div style="color: ${colors[type]};">[${time}] ${message}</div>`;
            debugDiv.scrollTop = debugDiv.scrollHeight;
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function renderMarkdown(text) {
            try {
                // 配置marked选项
                marked.setOptions({
                    breaks: true, // 支持换行
                    gfm: true,    // 支持GitHub Flavored Markdown
                    headerIds: false, // 不生成header id
                    mangle: false     // 不转义email地址
                });
                
                return marked.parse(text);
            } catch (error) {
                console.error('Markdown渲染错误:', error);
                return escapeHtml(text); // 如果渲染失败，回退到HTML转义
            }
        }
        
        function addMessage(type, content, loading = false) {
            const chatHistory = document.getElementById('chatHistory');
            const messageId = 'msg_' + Date.now();
            const messageEl = document.createElement('div');
            messageEl.className = `message-wrapper ${type}-message-wrapper`;
            messageEl.id = messageId;
            
            debugLog(`🎨 添加消息: type=${type}, loading=${loading}, id=${messageId}`, 'info');
            
            if (type === 'user') {
                messageEl.innerHTML = `
                    <div class="message user-message">
                        <div class="message-content">
                            <div class="message-text">${escapeHtml(content)}</div>
                        </div>
                        <div class="message-avatar user-avatar">👤</div>
                    </div>
                `;
            } else {
                messageEl.innerHTML = `
                    <div class="message ai-message">
                        <div class="message-avatar ai-avatar">🤖</div>
                        <div class="message-content">
                            ${loading ? 
                                `<div class="loading-state">
                                    <div class="loading-spinner">⚙️</div>
                                    <div class="loading-text">伯乐正在思考中...</div>
                                </div>` :
                                `<div class="message-text">${renderMarkdown(content)}</div>`
                            }
                        </div>
                    </div>
                `;
            }
            
            chatHistory.appendChild(messageEl);
            chatHistory.scrollTop = chatHistory.scrollHeight;
            
            return messageId;
        }
        
        function updateMessage(messageId, content) {
            debugLog(`✏️ 更新消息: ${messageId}`, 'info');
            const messageEl = document.getElementById(messageId);
            if (messageEl) {
                const messageContent = messageEl.querySelector('.message-content');
                if (messageContent) {
                    // AI消息使用markdown渲染，用户消息使用HTML转义
                    const isAiMessage = messageEl.classList.contains('ai-message-wrapper');
                    const renderedContent = isAiMessage ? renderMarkdown(content) : escapeHtml(content);
                    messageContent.innerHTML = `<div class="message-text">${renderedContent}</div>`;
                    debugLog(`✅ 消息更新成功: ${messageId} (markdown: ${isAiMessage})`, 'success');
                } else {
                    debugLog(`❌ 未找到 .message-content 元素: ${messageId}`, 'error');
                }
            } else {
                debugLog(`❌ 未找到消息元素: ${messageId}`, 'error');
            }
        }
        
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message || sending) return;
            
            testMessage(message);
            input.value = '';
        }
        
        async function testMessage(message) {
            if (sending) return;
            sending = true;
            
            debugLog(`🔍 发送命令: "${message}"`, 'info');
            debugLog(`📡 API URL: ${apiBaseUrl}/chat`, 'info');
            
            // 添加用户消息
            addMessage('user', message);
            
            // 添加AI思考消息
            const aiMessageId = addMessage('ai', '', true);
            debugLog(`🤖 创建AI消息: ${aiMessageId}`, 'info');
            
            try {
                const response = await fetch(`${apiBaseUrl}/chat`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });
                
                debugLog(`📊 响应状态: ${response.status} ${response.statusText}`, response.ok ? 'success' : 'error');
                
                if (!response.ok) {
                    const errorText = await response.text();
                    debugLog(`❌ HTTP错误内容: ${errorText}`, 'error');
                    updateMessage(aiMessageId, `网络请求失败: ${response.status} ${response.statusText}`);
                    return;
                }
                
                const data = await response.json();
                debugLog(`📋 响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                
                if (data.success) {
                    debugLog(`✅ 处理成功, 更新消息内容`, 'success');
                    updateMessage(aiMessageId, data.message || '处理完成');
                    
                    if (data.analyzed_candidates && data.analyzed_candidates.length > 0) {
                        debugLog(`📊 包含 ${data.analyzed_candidates.length} 个候选人数据`, 'info');
                    }
                } else {
                    debugLog(`❌ 服务器返回错误: ${data.error || '未知错误'}`, 'error');
                    updateMessage(aiMessageId, `抱歉，处理请求时出现错误：${data.error || '未知错误'}`);
                }
                
            } catch (error) {
                debugLog(`❌ 请求异常: ${error.message}`, 'error');
                updateMessage(aiMessageId, '抱歉，网络连接出现问题，请稍后重试。');
            } finally {
                sending = false;
                debugLog(`🔄 发送状态重置`, 'info');
            }
        }
        
        function clearChat() {
            document.getElementById('chatHistory').innerHTML = '';
            document.getElementById('debugLog').innerHTML = '';
            debugLog(`🧹 聊天记录已清空`, 'info');
        }
        
        // 页面加载完成后的初始化
        window.onload = () => {
            debugLog(`🚀 调试界面初始化完成`, 'success');
            debugLog(`🔧 API基础URL: ${apiBaseUrl}`, 'info');
            
            // 自动测试一次
            setTimeout(() => {
                debugLog(`🧪 执行自动测试...`, 'info');
                testMessage('你好');
            }, 1000);
        };
    </script>
</body>
</html>





